package net.oschina.android.ui.fragment;

import net.oschina.android.R;
import net.oschina.android.adapter.lasttweetadapter;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;

/**
 * @author HuangWenwei
 *
 * @date 2014年9月1日
 */
public class latestTweetFragment extends ListFragment implements OnScrollListener{
	
	private final int AUTOLOAD_THRESHOLD = 4;	//	当用户靠近底部为4时，加载数据
	private final int MAXIMUM_ITEMS = 52;
	private lasttweetadapter mAdapter;
	private View mFooterView;
	private Handler  mHandler;
	private boolean mIsLoading = false;
	private boolean mMoreDataAvailale = true;
	private boolean mWasLoading = false;
	
	private Runnable mAddItemsRunnable = new Runnable() {
		@Override
		public void run() {
			mAdapter.addMoreItems(10);
			mIsLoading = false;
		}
	};
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		final Context context = getActivity();
		mHandler = new Handler();
		mAdapter = new lasttweetadapter(context, android.R.layout.simple_list_item_1);
		mFooterView = LayoutInflater.from(context).inflate(R.layout.loading_view, null);
		getListView().addFooterView(mFooterView, null, false);
		setListAdapter(mAdapter);
		getListView().setOnScrollListener(this);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if(!mIsLoading && mMoreDataAvailale){
			if(totalItemCount >= MAXIMUM_ITEMS){
				mMoreDataAvailale = false;
				getListView().removeFooterView(mFooterView);
			}else if(totalItemCount - AUTOLOAD_THRESHOLD <= firstVisibleItem + visibleItemCount){
				mIsLoading = true;
				mHandler.postDelayed(mAddItemsRunnable, 1000);
			}
		}
	}
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}

	@Override
	public void onStart() {
		super.onStart();
		if(mWasLoading){
			mWasLoading = false;
			mIsLoading = true;
			mHandler.postDelayed(mAddItemsRunnable, 1000);
		}
	}

	@Override
	public void onStop() {
		super.onStop();
		mHandler.removeCallbacks(mAddItemsRunnable);
		mWasLoading = mIsLoading;
		mIsLoading = false;
	}
}
